package org.jeecg.talentCooperation.fruit.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.talentCooperation.fieldKeyword.mapper.FieldKeywordMapper;
import org.jeecg.talentCooperation.fruit.entity.FruitFieldRel;
import org.jeecg.talentCooperation.fruit.mapper.FruitAuthorMapper;
import org.jeecg.talentCooperation.fruit.mapper.FruitFieldRelMapper;
import org.jeecg.talentCooperation.fruit.mapper.FruitMapper;
import org.jeecg.talentCooperation.fruit.mapper.FruitResultMapper;
import org.jeecg.talentCooperation.fruit.model.FruitCommonResultModel;
import org.jeecg.talentCooperation.fruit.model.FruitResultModel;
import org.jeecg.talentCooperation.fruit.service.IFruitResultService;
import org.jeecg.talentCooperation.talent.entity.TalentBasic;
import org.jeecg.talentCooperation.talent.mapper.TalentBasicMapper;
import org.jeecg.talentCooperation.talent.model.TalentFruitResultModel;
import org.jeecg.talentCooperation.talent.model.TalentResultModel;
import org.jeecg.talentCooperation.util.keywords.TfIdfAnalyzer;
import org.jeecg.talentCooperation.wordcloud.mapper.WordcloudMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class FruitResultServiceImpl extends ServiceImpl<FruitResultMapper, FruitResultModel> implements IFruitResultService {

	@Autowired
	private TalentBasicMapper talentBasicMapper;
	@Autowired
	private FruitMapper fruitMapper;
	@Autowired
	private FruitAuthorMapper fruitAuthorMapper;
	@Autowired
	private FruitResultMapper fruitResultMapper;
	@Autowired
	private FruitFieldRelMapper fruitFieldRelMapper;
	@Autowired
	private FieldKeywordMapper fieldKeywordMapper;
	@Autowired
	private WordcloudMapper wordcloudMapper;
	@Autowired
	StringRedisTemplate redisTemplate;


	@Override
	public List<FruitCommonResultModel> getFruitTagByField(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getFruitTagByField(fruitResultModel);
	}

	@Override
	public Page<FruitResultModel> getHotFruit(Page<FruitResultModel> page, FruitResultModel fruitResultModel) {
		Page<FruitResultModel> list = fruitResultMapper.getViewFruitLog(page, fruitResultModel);
		if(!CollectionUtils.isEmpty(list.getRecords()) && list.getRecords().size() >= 10){
			return list;
		}
		return fruitResultMapper.getHotFruit(page, fruitResultModel);
	}


	@Override
	public Page<FruitResultModel> getFieldLinkFruit(Page<FruitResultModel> page, FruitResultModel fruitResultModel) {
		return fruitResultMapper.getFieldLinkFruit(page, fruitResultModel);
	}

	/**
	 * 设置查询条件
	 * @param fruitResultModel
	 */
	public void setSearchCondition(FruitResultModel fruitResultModel){
		// 分词
//		TfIdfAnalyzer tfIdfAnalyzer = new TfIdfAnalyzer();
//		List<String> contentList = tfIdfAnalyzer.keywords(fruitResultModel.getContent());
//		fruitResultModel.setContentList(contentList);

//		查询是否在专家表中名字对应上
		QueryWrapper<TalentBasic> faWrapper = new QueryWrapper();
		faWrapper.and(i -> i.like("real_name", fruitResultModel.getContent()));
		List<TalentBasic> talentBasicList = talentBasicMapper.selectList(faWrapper);
//		作者 过滤
		if(!CollectionUtils.isEmpty(talentBasicList)){
			fruitResultModel.setSearchType("2");
		}

		if(!ObjectUtils.isEmpty(fruitResultModel.getPubStartDate()) || !ObjectUtils.isEmpty(fruitResultModel.getPubStartDate()) ){
			List<String> authorIdList = fruitResultMapper.getAuthorIdByCondition(fruitResultModel);
			fruitResultModel.setTalentIdList(authorIdList);
		}
		if(!ObjectUtils.isEmpty(fruitResultModel.getFruitTypes())){
			List<String> authorIdList = fruitResultMapper.getAuthorIdByCondition(fruitResultModel);
			if(ObjectUtils.isEmpty(authorIdList)){
				//为空 不加标志位就 随机写一个不存在的id 为了结果集返回空
				authorIdList.add("aaaaaaaaaaaaaaa");
			}
			fruitResultModel.setTalentIdList(authorIdList);
		}
	}

	/**
	 * 设置查询成果条件
	 * @param fruitResultModel
	 */
	public void setSearchFruitCondition(FruitResultModel fruitResultModel){
		QueryWrapper<FruitFieldRel> fruitFieldQueryWrapper = new QueryWrapper();
		fruitFieldQueryWrapper.and(i -> i.like("fruit_keyword", fruitResultModel.getContent()).or().like("fk_name", fruitResultModel.getContent()));
		List<FruitFieldRel> fruitFieldRels = fruitFieldRelMapper.selectList(fruitFieldQueryWrapper);
		fruitResultModel.setFruitIdList(fruitFieldRels.stream().map(FruitFieldRel::getFruitId).collect(Collectors.toSet()));
	}

	@Override
	public Page<TalentFruitResultModel> getTalentDataBySearchContent(Page<TalentFruitResultModel> page, FruitResultModel fruitResultModel) {
		setSearchCondition(fruitResultModel);
		//如果没有匹配上 直接返回空
//		if(!("2").equals(fruitResultModel.getSearchType()) && ObjectUtils.isEmpty(fruitResultModel.getFieldValues())){
//			return page.setRecords(Collections.emptyList());
//		}
		return page.setRecords(fruitResultMapper.getTalentDataBySearchContent(page, fruitResultModel));
	}

	@Override
	public Page<FruitResultModel> getFruitListOfPage(Page<FruitResultModel> page, FruitResultModel fruitResultModel) {
		return page.setRecords(fruitResultMapper.getFruitList(page, fruitResultModel));
	}

	@Override
	public int getFruitTotal(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getFruitTotal(fruitResultModel);
	}

	@Override
	public Map getTalentGroupDataBySearchContentOfList(FruitResultModel fruitResultModel) {
		this.setSearchFruitCondition(fruitResultModel);

		//分页
		int fromIndex = fruitResultModel.getPageSize()*(fruitResultModel.getPageNo() - 1);
		int toIndex = fruitResultModel.getPageSize()*(fruitResultModel.getPageNo());

		List<TalentFruitResultModel> list = fruitResultMapper.getTalentGroupDataBySearchContent(fruitResultModel);

		//#获取当前页数据
		toIndex = Math.min(list.size(), toIndex);

		List<TalentFruitResultModel> resultList = list.subList(fromIndex,toIndex);

		Integer pageNo = fruitResultModel.getPageNo();
		Integer pageSize = fruitResultModel.getPageSize();

		fruitResultModel.setPageNo((pageNo - 1) * pageSize);
		fruitResultModel.setPageSize(pageSize);
		Page<TalentFruitResultModel> page = new Page<TalentFruitResultModel>(pageNo, pageSize);


		page.setRecords(resultList);
		page.setTotal(list.size());

		Map map = new HashMap();
		map.put("talentInfoList", page);

		//获取研究领域
		Map<String, Integer> fieldMap = new HashMap<>();
		list.forEach(frm -> {
			String[] fieldNameArr = frm.getField().split(";");
			for (String fieldName : fieldNameArr) {
//				if (fieldName.contains(",")) {
//					String[] talentResNameArr = fieldName.split(",");
//					for (String f : talentResNameArr) {
//						if(fieldMap.get(f) != null){
//							fieldMap.merge(f, fieldMap.get(f), Integer::sum);
//						}else{
//							fieldMap.putIfAbsent(f, 1);
//						}
//					}
//				}else{
				if(fieldMap.get(fieldName) != null){
					fieldMap.merge(fieldName, 1, Integer::sum);
				}else{
					fieldMap.putIfAbsent(fieldName, 1);
				}
//				}
			}
		});
		List<FruitCommonResultModel> fcrList = new ArrayList<>();
		fieldMap.forEach((key, value) -> {
			FruitCommonResultModel fcm = new FruitCommonResultModel();
			fcm.setName(key);
			fcm.setCount(value);
			fcrList.add(fcm);
		});
		map.put("fieldPageList", fcrList.stream().sorted(Comparator.comparing(FruitCommonResultModel::getCount).reversed()).collect(Collectors.toList()).subList(0, Math.min(fcrList.size(), 10)));

		//获取合作部门
		Map<String, Integer> deptMap = new HashMap<>();
		list.forEach(frm -> {
			if(!StringUtils.isEmpty(frm.getOrgName())){
				String[] orgNameArr = frm.getOrgName().split(";");
				for (String orgName : orgNameArr) {
					if(!StringUtils.isEmpty(orgName)){
						if(deptMap.get(orgName) != null){
							deptMap.merge(orgName, deptMap.get(orgName), Integer::sum);
						}else{
							deptMap.putIfAbsent(orgName, 1);
						}
					}
				}
			}
		});
		List<FruitCommonResultModel> deptList = new ArrayList<>();
		deptMap.forEach((key, value) -> {
			FruitCommonResultModel fcm = new FruitCommonResultModel();
			fcm.setName(key);
			fcm.setCount(value);
			deptList.add(fcm);
		});
		map.put("deptPageList", deptList.stream().sorted(Comparator.comparing(FruitCommonResultModel::getCount).reversed()).collect(Collectors.toList()).subList(0, Math.min(deptList.size(), 10)));

		return map;
	}


//	public List<Long> getFruitIdList(FruitResultModel fruitResultModel){
//		if(StringUtils.isEmpty(fruitResultModel.getContent())){
//			return null;
//		}
//		Set<Long> fruitIdList = new HashSet<>();
//		if(fruitResultModel.getSearchType().equals("0") || fruitResultModel.getSearchType().equals("1")){
//			//查询是否在专家表中名字对应上
//			QueryWrapper<FruitAuthor> faWrapper = new QueryWrapper();
//			faWrapper.and(i -> i.like("author", fruitResultModel.getContent()));
//			List<FruitAuthor> fruitAuthorList = fruitAuthorMapper.selectList(faWrapper);
//			//作者 过滤
//			if(!CollectionUtils.isEmpty(fruitAuthorList)){
////				fruitIdList = fruitAuthorList.stream().map(FruitAuthor::getFruitId).collect(Collectors.toList());
//				fruitResultModel.setSearchType("2");
//			}else{
//				//综合检索及主题 过滤fruitId
////				List<String> resultList = new ArrayList<>();
////				resultList.add(fruitResultModel.getContent());
////				List<String> resultList = chatGptUtil.getKeyWordsAndSynonymsWord(fruitResultModel.getContent());
////				//近义词匹配
////				QueryWrapper<WordSynonymsPo> wsWrapper = new QueryWrapper();
////				if(!CollectionUtils.isEmpty(resultList)){
////					for (String keyword : resultList) {
////						wsWrapper.or(i -> i.like("name", keyword));
////					}
////				}
////				List<WordSynonymsPo> wordSynonyms = wordSynonymsMapper.selectList(wsWrapper);
////				fruitIdList.addAll(wordSynonyms.stream().map(WordSynonymsPo::getFruitId).collect(Collectors.toList()));
//
//				//成果名称匹配
////				QueryWrapper<Fruit> fruitWrapper = new QueryWrapper();
////				for (String keyword : resultList) {
////					fruitWrapper.or(i -> i.like("name", keyword));
////				}
////				fruitWrapper.select("id");
////				List<Object> fruitList = fruitMapper.selectObjs(fruitWrapper);
////				fruitIdList.addAll(fruitList.stream().map(idObject -> Long.valueOf(idObject.toString())).collect(Collectors.toList()));
////				fruitResultModel.setName(fruitResultModel.getContent());
//
//				//从主页点击的关键词匹配 第二个页面点击 也需要查询
//				QueryWrapper<WordcloudPo> wcQueryWrapper = new QueryWrapper();
//				wcQueryWrapper.and(i -> i.like("name", fruitResultModel.getContent()));
//				List<WordcloudPo> wcFruitList = wordcloudMapper.selectList(wcQueryWrapper);
//				if(!CollectionUtils.isEmpty(wcFruitList)){
//					fruitIdList.addAll(wcFruitList.stream().map(WordcloudPo::getFruitId).collect(Collectors.toList()));
//				}
//				//成果名称匹配  第二个页面点击 也需要查询
//				QueryWrapper<Fruit> fruitWrapper = new QueryWrapper();
//				fruitWrapper.or(i -> i.like("name", fruitResultModel.getContent()));
//				List<Fruit> fruitList = fruitMapper.selectList(fruitWrapper);
//				if(!CollectionUtils.isEmpty(fruitList)){
//					fruitIdList.addAll(fruitList.stream().map(Fruit::getId).collect(Collectors.toList()));
//				}else{
//					// 如果不返回 会查询所有 因此写一个不存在的 id
//					fruitIdList.add(111L);
//				}
//
//				//领域匹配 过滤fruitId  勾选了以勾选为主
////				if(fruitResultModel.getFieldNames() == null || fruitResultModel.getFieldNames().length == 0){
////					if(fruitResultModel.getSearchType().equals("0") && !CollectionUtils.isEmpty(resultList)){
////						fruitResultModel.setFields(resultList.toArray(new String[resultList.size()]));
////						List<Long> fieldFruitIdList =  fruitResultMapper.getFieldFruitId(fruitResultModel);
////						fruitIdList.addAll(fieldFruitIdList);
////					}
////				}
//
////				StringBuilder ss = new StringBuilder();
////				for (Long id : fruitIdList) {
////					ss.append("'").append(id).append("'").append(",");
////				}
////				System.out.println("生成的synonyms中getFruitId---" + ss.toString());
//			}
//		}else if(fruitResultModel.getSearchType().equals("3")){
//			//领域分词后匹配  ---  检索条件已丢弃
////			List<String> resultList = chatGptUtil.getKeyWordsAndSynonymsWord(fruitResultModel.getContent());
////			if(!CollectionUtils.isEmpty(resultList)){
////				//勾选了以勾选为主
////				if(fruitResultModel.getFieldNames() == null || fruitResultModel.getFieldNames().length == 0){
////					fruitResultModel.setFieldNames(resultList.toArray(new String[resultList.size()]));
////				}
////			}
//		}
//		return new ArrayList<>(fruitIdList);
//	}

//	@Override
//	public Page<TalentFruitResultModel> getTalentGroupDataBySearchContentOfPage(Page<TalentFruitResultModel> page, FruitResultModel fruitResultModel) {
//		this.setModelFruitIdList(fruitResultModel);
//		return page.setRecords(fruitResultMapper.getTalentGroupDataBySearchContentOfPage(page, fruitResultModel));
//	}

	@Override
	public List<FruitCommonResultModel> getFruitFieldGroupCount(FruitResultModel fruitResultModel) {
		this.setSearchCondition(fruitResultModel);
		List<FruitCommonResultModel>  fruitResultModelList = fruitResultMapper.getFruitFieldGroupCount(fruitResultModel);
		List<FruitCommonResultModel> list = new ArrayList<>();
		if(!ObjectUtils.isEmpty(fruitResultModelList)){
			Map<String, Integer> countMap = new HashMap<>();
			for (FruitCommonResultModel resultModel : fruitResultModelList) {
				// 将字符串按逗号分割成数组
				String[] fields = resultModel.getName().split(",");
				// 遍历数组，对每个字段进行计数
				for (String field : fields) {
					// 去除字段值中的前后空格
					String trimmedField = field.trim();
					// 如果Map中已有该字段，则增加其计数，否则添加到Map中
					countMap.put(trimmedField, countMap.getOrDefault(trimmedField, 0) + 1);
				}
			}
			for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
				list.add(new FruitCommonResultModel(entry.getKey(), entry.getValue()));
			}
		}
		return fruitResultModelList;
	}

	@Override
	public Page<FruitCommonResultModel> getFruitDeptGroupCount(Page<FruitCommonResultModel> page, FruitResultModel fruitResultModel) {
		this.setSearchFruitCondition(fruitResultModel);
		return page.setRecords(setResultData(fruitResultMapper.getFruitDeptGroupCount(page, fruitResultModel)));
	}

	private List<FruitCommonResultModel> setResultData(List<FruitCommonResultModel> queryList){
		List<FruitCommonResultModel> resultList = new ArrayList<>();
		Map<String, Integer> map = new HashMap<>();
		queryList.forEach(fcr -> {
			String mapKey = fcr.getName();
			if (mapKey.contains(";")) {
				String[] talentResNameArr = mapKey.split(";");
				for (String s : talentResNameArr) {
					mapKey = s;
					map.merge(mapKey, fcr.getCount(), Integer::sum);
				}
			}else{
				map.merge(mapKey, fcr.getCount(), Integer::sum);
			}
		});
		map.forEach((key, value) -> {
			FruitCommonResultModel fcr = new FruitCommonResultModel();
			fcr.setName(key);
			fcr.setCount(value);
			resultList.add(fcr);
		});
		return resultList;
	}

	@Override
	public List<TalentBasic> getTalentBasicData(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getTalentBasicData(fruitResultModel);
	}

	@Override
	public List<FruitResultModel> getFruitChart(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getFruitChart(fruitResultModel);
	}

	@Override
	public List<TalentResultModel> getRelatedTalentChart(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getRelatedTalentChart(fruitResultModel);
	}

	@Override
	public List<FruitCommonResultModel> getTalentFieldTagData(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getTalentFieldTagData(fruitResultModel);
	}

	@Override
	public List<FruitResultModel> getRecommendTalent(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getRecommendTalent(fruitResultModel);
	}

	@Override
	public List<FruitResultModel> getResearchFieldData(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getResearchFieldData(fruitResultModel);
	}

	@Override
	public List<FruitCommonResultModel> getMostFieldDataOfNum(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getMostFieldDataOfNum(fruitResultModel);
	}

	@Override
	public List<FruitResultModel> getAuthorDataOfHotField(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getAuthorDataOfHotField(fruitResultModel);
	}

	@Override
	public List<FruitResultModel> getAuthorDataOfTypeField(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getAuthorDataOfTypeField(fruitResultModel);
	}


	@Override
	public List<FruitResultModel> getFruitWordCloud(FruitResultModel fruitResultModel) {
		return fruitResultMapper.getFruitWordCloud(fruitResultModel);
	}
}
